const MqttConnector = require('../common/mqtt-connector');
const LedModule = require('./led');
const TemperatureSensorModule = require('./temperature');
const ServoModule = require('./servo');
// 导入大气压传感器模块
const BarometricPressureSensorModule = require('./barometric-pressure');

// MQTT broker地址
const BROKER_URL = 'mqtt://192.168.1.21';

// 设备ID（可根据实际情况修改）
const DEVICE_ID = 'iot-test-box-001';

// 创建MQTT连接器实例
const mqttConnector = new MqttConnector(BROKER_URL, 'iot-device-simulator');

// 创建设备模块实例
const ledModule = new LedModule(DEVICE_ID);
const temperatureModule = new TemperatureSensorModule(DEVICE_ID);
const servoModule = new ServoModule(DEVICE_ID);
// 创建大气压传感器模块实例
const barometricPressureModule = new BarometricPressureSensorModule(DEVICE_ID);

// 启动设备模拟
async function startDevice() {
  try {
    // 连接到MQTT broker
    await mqttConnector.connect();

    // 初始化LED模块
    await ledModule.init(mqttConnector);

    // 初始化温度传感器模块
    await temperatureModule.init(mqttConnector);
    temperatureModule.startSending();

    // 初始化舵机模块
    await servoModule.init(mqttConnector);

    // 初始化大气压传感器模块
    await barometricPressureModule.init(mqttConnector);
    barometricPressureModule.startSending();

    console.log('IoT设备模拟器已成功启动');
    console.log('LED模块就绪，可以接收控制命令');
    console.log('温度传感器模块已开始发送数据');
    console.log('舵机模块就绪，可以接收控制命令');
    console.log('大气压传感器模块已开始发送数据');
  } catch (error) {
    console.error(`启动设备模拟器失败: ${error.message}`);
    process.exit(1);
  }
}

// 处理进程终止信号
process.on('SIGINT', () => {
  console.log('正在关闭设备模拟器...');
  temperatureModule.stopSending();
  barometricPressureModule.stopSending(); // 停止大气压传感器数据发送
  mqttConnector.disconnect();
  process.exit(0);
});

// 启动设备
startDevice();